package com.tensquare.friend.controller;

import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.friend.feign.UserClient;
import com.tensquare.friend.service.FriendService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/friend")
@CrossOrigin
public class FriendController {
    @Autowired
    private FriendService friendService;
    @Autowired
    private UserClient userClient;

    /**
     * 添加好友或非好友
     *
     * @param friendid
     * @param type
     * @param request
     * @return
     */
    @RequestMapping(value = "/like/{friendid}/{type}", method = RequestMethod.PUT)
    public Result addFriendOrNoFriend(@PathVariable("friendid") String friendid,
                                      @PathVariable("type") String type,
                                      HttpServletRequest request) {
        Claims claims = (Claims) request.getAttribute("Authorization_USER");
        if (claims != null) {
            int flag = friendService.save(claims.getId(), friendid, type);
            if (flag == 1) {
                return new Result(false, StatusCode.PER_ERROR, "请勿重复添加");
            }
            if (flag == 0) {
                userClient.updateFanscountAndFollowcount(claims.getId(), friendid, 1);
            }
            return new Result(true, StatusCode.OK, "添加成功");
        }
        return new Result(false, StatusCode.ACCESS_ERROR, "权限不足");
    }

    /**
     * 删除好友
     *
     * @param friendid
     * @param request
     * @return
     */
    @DeleteMapping("/{friendid}")
    public Result deleteFriend(@PathVariable("friendid") String friendid,
                               HttpServletRequest request) {
        Claims claims = (Claims) request.getAttribute("Authorization_USER");
        if (claims != null) {
            friendService.deleteFriend(claims.getId(), friendid);
            userClient.updateFanscountAndFollowcount(claims.getId(), friendid, -1);
            return new Result(true, StatusCode.OK, "删除成功");
        }
        return new Result(false, StatusCode.ACCESS_ERROR, "权限不足");
    }
}
